﻿using Grpc.Core;
using Grpc.Core.Interceptors;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace GrpcClient
{
    /// <summary>
    /// 客户端grpc拦截器
    /// https://www.cnblogs.com/stulzq/p/11840535.html
    /// </summary>
    public class ClientLoggerInterceptor : Interceptor
    {
        public override TResponse BlockingUnaryCall<TRequest, TResponse>(TRequest request, ClientInterceptorContext<TRequest, TResponse> context, BlockingUnaryCallContinuation<TRequest, TResponse> continuation)
        {
            var initialColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"BlockingUnaryCall call. Type: {context.Method.FullName}. Request: {typeof(TRequest)}. Response: {typeof(TResponse)}");
            Console.ForegroundColor = initialColor;


            return base.BlockingUnaryCall(request, context, continuation);
        }
        public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
            TRequest request,
            ClientInterceptorContext<TRequest, TResponse> context,
            AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
        {
            //LogCall(context.Method);
            //var headers = new Metadata { { "InterceptorHeader", $"username" } };
            //context.Options.WithHeaders(headers);   
            //return continuation(request, context);

            //通过拦截注入header，后续可以在这里注入用户信息
            Console.WriteLine("客户端调用执行开始");
            var headers = new Metadata { { "InterceptorHeader", $"username" } };
            var option= context.Options.WithHeaders(headers);
            var newContext= new ClientInterceptorContext<TRequest, TResponse>(context.Method, context.Host, option);
            var responseCon = continuation(request, newContext);
            var response = new AsyncUnaryCall<TResponse>(responseCon.ResponseAsync, responseCon.ResponseHeadersAsync, responseCon.GetStatus, responseCon.GetTrailers, responseCon.Dispose);
            Console.WriteLine("客户端调用执行结束");
            return response;


        }

        private void LogCall<TRequest, TResponse>(Method<TRequest, TResponse> method)
            where TRequest : class
            where TResponse : class
        {
            var initialColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Starting call. Type: {method.Type}. Request: {typeof(TRequest)}. Response: {typeof(TResponse)}");
            Console.ForegroundColor = initialColor;
        }
    }
}
